// 连接池性能监控和优化建议模块
import { dbPool } from './database.js';

class ConnectionPoolOptimizer {
  constructor() {
    this.stats = {
      totalConnections: 0,
      idleConnections: 0,
      waitingClients: 0,
      totalQueries: 0,
      failedQueries: 0,
      connectionErrors: 0,
      lastCheck: new Date(),
      checkInterval: 30000 // 30秒检查一次
    };
    
    this.startMonitoring();
  }

  // 开始监控连接池性能
  startMonitoring() {
    setInterval(() => {
      this.collectStats();
      this.analyzePerformance();
      this.suggestOptimizations();
    }, this.stats.checkInterval);
  }

  // 收集连接池统计信息
  collectStats() {
    this.stats.totalConnections = dbPool.totalCount || 0;
    this.stats.idleConnections = dbPool.idleCount || 0;
    this.stats.waitingClients = dbPool.waitingCount || 0;
    this.stats.lastCheck = new Date();
  }

  // 分析性能指标
  analyzePerformance() {
    const utilization = this.stats.totalConnections > 0 
      ? ((this.stats.totalConnections - this.stats.idleConnections) / this.stats.totalConnections) * 100 
      : 0;
    
    const waitingRatio = this.stats.totalConnections > 0 
      ? (this.stats.waitingClients / this.stats.totalConnections) * 100 
      : 0;

    console.log('📊 连接池性能分析:');
    console.log(`  总连接数: ${this.stats.totalConnections}`);
    console.log(`  空闲连接: ${this.stats.idleConnections}`);
    console.log(`  等待客户端: ${this.stats.waitingClients}`);
    console.log(`  连接利用率: ${utilization.toFixed(1)}%`);
    console.log(`  等待比例: ${waitingRatio.toFixed(1)}%`);

    // 性能警告
    if (waitingRatio > 50) {
      console.warn('⚠️ 连接池负载过高，大量客户端在等待连接');
    }

    if (utilization > 80) {
      console.warn('⚠️ 连接池利用率过高，考虑增加最大连接数');
    }

    if (this.stats.waitingClients > 10) {
      console.error('🚨 连接池严重过载，建议立即优化');
    }
  }

  // 提供优化建议
  suggestOptimizations() {
    const suggestions = [];

    // 基于当前统计数据的建议
    if (this.stats.waitingClients > 5) {
      suggestions.push({
        type: 'critical',
        message: '增加最大连接数 (max)',
        reason: `当前有 ${this.stats.waitingClients} 个客户端在等待连接`,
        action: '将 max 参数增加到 20-30'
      });
    }

    if (this.stats.idleConnections > this.stats.totalConnections * 0.8) {
      suggestions.push({
        type: 'optimization',
        message: '减少最小连接数 (min)',
        reason: '空闲连接过多，资源浪费',
        action: '将 min 参数减少到 2-5'
      });
    }

    if (this.stats.totalConnections === 0 && this.stats.waitingClients > 0) {
      suggestions.push({
        type: 'warning',
        message: '检查连接超时设置',
        reason: '连接池无法建立连接',
        action: '增加 connectionTimeoutMillis 和 acquireTimeoutMillis'
      });
    }

    // 环境特定的建议
    if (process.env.NODE_ENV === 'production') {
      suggestions.push({
        type: 'best-practice',
        message: '生产环境优化',
        reason: '生产环境需要更稳定的连接',
        action: '设置 max=20, min=5, acquireTimeoutMillis=30000'
      });
    }

    // 输出建议
    if (suggestions.length > 0) {
      console.log('💡 连接池优化建议:');
      suggestions.forEach(suggestion => {
        const icon = suggestion.type === 'critical' ? '🚨' : '💡';
        console.log(`${icon} ${suggestion.message}`);
        console.log(`   原因: ${suggestion.reason}`);
        console.log(`   建议: ${suggestion.action}`);
      });
    }
  }

  // 获取当前配置建议
  getOptimalConfig() {
    const env = process.env.NODE_ENV || 'development';
    
    const configs = {
      development: {
        max: 10,
        min: 2,
        connectionTimeoutMillis: 5000,
        acquireTimeoutMillis: 15000,
        idleTimeoutMillis: 30000
      },
      production: {
        max: 20,
        min: 5,
        connectionTimeoutMillis: 10000,
        acquireTimeoutMillis: 30000,
        idleTimeoutMillis: 30000
      },
      highTraffic: {
        max: 50,
        min: 10,
        connectionTimeoutMillis: 15000,
        acquireTimeoutMillis: 60000,
        idleTimeoutMillis: 60000
      }
    };

    return configs[env] || configs.development;
  }

  // 测试连接池性能
  async testPerformance() {
    console.log('🧪 连接池性能测试...');
    
    const startTime = Date.now();
    const testQueries = 10;
    let successfulQueries = 0;
    
    for (let i = 0; i < testQueries; i++) {
      try {
        await dbPool.query('SELECT 1');
        successfulQueries++;
      } catch (error) {
        console.warn(`查询 ${i+1} 失败:`, error.message);
      }
    }
    
    const endTime = Date.now();
    const duration = endTime - startTime;
    const avgTime = duration / testQueries;
    
    console.log(`✅ 性能测试完成:`);
    console.log(`   成功查询: ${successfulQueries}/${testQueries}`);
    console.log(`   总耗时: ${duration}ms`);
    console.log(`   平均查询时间: ${avgTime.toFixed(2)}ms`);
    
    // 性能评估
    if (avgTime > 100) {
      console.warn('⚠️ 查询性能较慢，建议优化连接池配置');
    } else if (avgTime > 50) {
      console.log('ℹ️ 查询性能正常');
    } else {
      console.log('🎉 查询性能优秀');
    }
  }
}

// 创建优化器实例
export const poolOptimizer = new ConnectionPoolOptimizer();

export default ConnectionPoolOptimizer;